using System.Collections;
using System.Collections.Generic;
using UnityEngine;

public class Enemy_BattleState : EnemyStateBase
{
    private float lastTimeWasInBattle;
    private Transform target;
    private Transform lastTarget;
    private Transform newTarget;
    protected float lastTimeAttacked;
    public Enemy_BattleState(Enemy enemy, StateMachine stateMachine, string animName) : base(enemy, stateMachine, animName)
    {
        lastTimeAttacked -= enemy.attackCooldown;
    }
    public override void Enter()
    {
        base.Enter();

        //在敌人进入战斗状态时更新敌人检测到玩家后的时间
        UpdateLastTimeWasInBattle();

        GetChaseTarget();
        //player ??= enemy.PlayerDetected().transform;
        //player ??= enemy.player;
        //如果玩家应该后撤
        if (ShouldRetreat())
        {
            enemy.SetVelocity(enemy.retreatMovement.x * -MoveDirection(), enemy.retreatMovement.y);
            enemy.HandleFlip(MoveDirection());
        }
    }

    public override void Update()
    {
        if (enemy.PlayerDetected())
        {
            UpdateLastTimeWasInBattle();
            UpdateTargetIfNeeded();
        }

        //如果战斗时间结束（脱离战斗时间结束）
        if (BattleTimeIsOver())
            stateMachine.ChangeState(enemy.idleState);

        //如果玩家在敌人攻击范围内并且敌人检测到玩家
        if (WithInAttackRange() && enemy.PlayerDetected() && CanAttack())
        {
            stateMachine.ChangeState(enemy.attackState); //敌人发动攻击
            lastTimeAttacked = Time.time;
        }
        else //继续追踪
        {
            
            //如果玩家没有进入最小追踪范围，持续追踪
                if (IsInMinTrace() == false)
                {
                    float xVelocity = enemy.canChase ? enemy.GetBattleSpeed() : 0;
                    enemy.SetVelocity(xVelocity * MoveDirection(), rb.velocity.y);
                }
        }
    }

    public bool CanAttack() => Time.time > lastTimeAttacked + enemy.attackCooldown;

    protected void UpdateTargetIfNeeded()
    {
        newTarget = enemy.PlayerDetected().transform;
        if (lastTarget != newTarget)
        {
            target = newTarget;
            lastTarget = newTarget;
        }
    }
 
    //得到敌人追踪目标
    private void GetChaseTarget()
    {
        //获得检测的玩家位置
        if (target == null)
            target = enemy.PlayerDetected().transform;

        //当玩家攻击敌人时敌人进入战斗状态,如果敌人没有检测到玩家，此时player==null，则执行，将追击的玩家设置为敌人受击的攻击者
        if (target == null)
            target = enemy.player;
        //当目标不为空，且目标没有显示时，判断目标的SpriteRenderer是否有渲染图片，即判断SpriteRenderer是否有勾选
        //如果目标没有图片渲染，则将目标设置为玩家
        SpriteRenderer targetSprite = target.GetComponentInChildren<SpriteRenderer>();
        if (targetSprite != null && targetSprite.enabled == false)
            target = enemy.player;

    }
    //判断玩家是否处于攻击范围内
    protected bool WithInAttackRange() => enemy.attackDistance > DistanceToPlayer();
    //判断玩家战斗状态是否结束
    protected bool BattleTimeIsOver() => Time.time > lastTimeWasInBattle + enemy.battleTimeDuration;
    //更新敌人检测到玩家后的时间
    protected void UpdateLastTimeWasInBattle() => lastTimeWasInBattle = Time.time;
    //获得敌人和玩家的水平位移差,固定为正值
    protected float DistanceToPlayer()
    {
        if (target == null)
            return float.MaxValue;
        return Mathf.Abs(target.position.x - enemy.transform.position.x);
    }
    //获得玩家相对于敌人的方向
    protected int MoveDirection()
    {
        if (target == null)
        {
            return 0;
        }
        return target.position.x > enemy.transform.position.x ? 1 : -1;
    }
    protected bool IsInMinTrace() => DistanceToPlayer() < enemy.minTraceDistance;
    //判断敌人是否应该后撤
    protected bool ShouldRetreat() => enemy.minRetreatDistacnce > DistanceToPlayer();
}
